package com.leetcode.easy;

/**
 * @Classname SolutionRemoveElement
 * @Description 移除数组中的元素
 * @Date 2020/8/19 15:57
 * @Created by zfl
 */
public class SolutionRemoveElement {
    /*
    *@Description 移除数组中的元素，双指针法
    *@param [nums, val]
    *@return int
    * 执行用时：0 ms, 在所有 Java 提交中击败了100.00%的用户
    * 内存消耗：38.3 MB, 在所有 Java 提交中击败了38.93%的用户
    */
    public int removeElement(int[] nums,int val) {
        int p = 0;
        int q = 1;
        int temp;
        if(nums.length > 1) {
            while (q < nums.length) {
                if(nums[p] != val) {
                    p++;
                    q = p;
                }else {
                    //nums[p] == val
                    if(nums[q] == val) {
                        q++;
                    }else {
                        temp = nums[p];
                        nums[p] = nums[q];
                        nums[q] = temp;
                        p++;
                        q++;
                    }
                }
            }
        }else if(nums.length == 1) {
            if(nums[p] != val) p++;
        }
        return p;
    }
    /*
    *@Description 拷贝覆盖
    *@param [nums, val]
    *@return int
    */
    public int removeElementTwo(int[] nums,int val) {
        int ans = 0;
        for (int num : nums) {
            if(num != val) {
                nums[ans] = num;
                ans++;
            }
        }
        return ans;
    }
    public int removeElementThree(int[] nums,int val) {
        int ans = nums.length;
        for (int i = 0; i < ans;) {
            if(nums[i] == val) {
                nums[i] = nums[val - 1];
                ans--;
            }else {
                i++;
            }
        }
        return ans;
    }
}
